#!/usr/bin/python
# -*- coding: UTF-8 -*-

import json
import traceback
from config.config import (
    LOG_LEVEL,
    LOG_LEVEL_DEBUG,
    LOG_LEVEL_INFO,
    LOG_LEVEL_ERROR,
    LOG_IP_SOURCE,
    LOG_CODE_POSITION,
    LOG_REDIS_APP,
    LOG_REDIS_MODEL,
    LOG_REDIS_ONOFF,
)
import sys
from utils.redis.redis import GetInstance
from utils.utils import (
    get_host_ip,
    get_host_name,
    get_utc_time,
    get_local_time,
)


class Log(object):
    """Log"""

    def __init__(self, tag, onoff=True):
        super(Log, self).__init__()
        self.tag = "[" + tag + "] "
        self.onoff = onoff
        self.redis = GetInstance()

    def _output(self, level, msg):
        if self.onoff == False or LOG_LEVEL < level:
            return
        # 往redis写还是文件。。。
        try:
            ti = sys._getframe(2)
            outstr = ""
            if LOG_IP_SOURCE:
                outstr += "from %s[%s] " % (get_host_ip(), get_host_name())
            if LOG_CODE_POSITION:
                outstr += "%s in func %s at line %s =>" % (
                    ti.f_code.co_filename,
                    ti.f_code.co_name,
                    str(ti.f_back.f_lineno),
                )
            outstr += get_local_time("%Y-%m-%d %H:%M:%S ")
            if LOG_REDIS_ONOFF == True:
                self.redis.lpush(
                    LOG_REDIS_APP,
                    LOG_REDIS_MODEL + "=" + outstr + self.tag + msg + "\r\n",
                )
            else:
                print(outstr + self.tag + msg)
        except Exception as e:
            print("redis lpush err", e)

    def _msg_pack(self, msgitem):
        try:
            if type(msgitem) in (list, tuple, dict, set):
                msgitem = json.dumps(msgitem, ensure_ascii=False)
            elif type(msgitem) == datetime.datetime:
                msgitem = msgitem.strftime("%Y-%m-%d %H:%M:%S")
        except:
            pass
        try:
            return "%s " % str(msgitem)
        except Exception as e:
            print("err ", e)
            return msgitem

    def Debug(self, *param):
        """Debug(self, *param)"""
        msg = ""
        try:
            for item in param:
                msg += self._msg_pack(item)
            self._output(LOG_LEVEL_DEBUG, msg)
        except Exception as e:
            print(e)

    def Info(self, *param):
        """Info(self, *param)"""
        try:
            msg = ""
            for item in param:
                msg += self._msg_pack(item)
            self._output(LOG_LEVEL_INFO, msg)
        except Exception as e:
            print(e)

    def Error(self, *param):
        """Error(self, *param)"""
        try:
            msg = ""
            for item in param:
                msg += self._msg_pack(item)
            self._output(LOG_LEVEL_ERROR, msg)
        except Exception as e:
            print(e)

    def Except(self, *param):
        """Except(self, *param)"""
        msg = traceback.format_exc()
        try:
            for item in param:
                msg += self._msg_pack(item)
            self._output(LOG_LEVEL_ERROR, msg)
        except Exception as e:
            print(e)
